#include "terrain.h"

namespace test {
	namespace graffiti {

void addQuad(const glm::vec3& offset, const glm::ivec4& indices, glm::vec3* positions,
			 const glm::vec3& normal, unsigned int* indexBuffer, Vertex* vertexBuffer, unsigned int& verticesCount,
			 unsigned int& indicesCount)
{
	for (unsigned int i = 0; i < 4; ++i)
	{
		Vertex& vertex(vertexBuffer[verticesCount + i]);

		vertex.position = offset + positions[indices[i]];
		vertex.normal = normal;
		vertex.uv.x = positions[indices[i]].x;
		vertex.uv.y = positions[indices[i]].y;
	}

	indexBuffer[indicesCount++] =  0 + verticesCount;
	indexBuffer[indicesCount++] =  2 + verticesCount;
	indexBuffer[indicesCount++] =  1 + verticesCount;
	indexBuffer[indicesCount++] =  0 + verticesCount;
	indexBuffer[indicesCount++] =  3 + verticesCount;
	indexBuffer[indicesCount++] =  2 + verticesCount;

	verticesCount += 4;
}

void addFace(const glm::vec3& position, Material mat, CubeFace face, unsigned int* indexBuffer, Vertex* vertexBuffer,
			 unsigned int& verticesCount, unsigned int& indicesCount)
{
	static glm::vec3 positions[8] = {
		glm::vec3(0.0f, 0.0f, 0.0f),
		glm::vec3(0.0f, 0.0f, 1.0f),
		glm::vec3(1.0f, 0.0f, 1.0f),
		glm::vec3(1.0f, 0.0f, 0.0f),
		glm::vec3(0.0f, 1.0f, 0.0f),
		glm::vec3(0.0f, 1.0f, 1.0f),
		glm::vec3(1.0f, 1.0f, 1.0f),
		glm::vec3(1.0f, 1.0f, 0.0f)
	};

	glm::vec3 normal;
	glm::ivec4 indices;

	switch (face)
	{
	case CubeFace_Front :
		normal = glm::vec3(0.0f, 0.0f, 1.0f);
		indices = glm::ivec4(6, 2, 1, 5);
		break ;
	case CubeFace_Back :
		normal = glm::vec3(0.f, 0.f, -1.f);
		indices = glm::ivec4(4, 0, 3, 7);
		break ;
	case CubeFace_Left :
		normal = glm::vec3(1.f, 0.f, 0.f);
		indices = glm::ivec4(7, 3, 2, 6);
		break ;
	case CubeFace_Right :
		normal = glm::vec3(-1.f, 0.f, 0.f);
		indices = glm::ivec4(5, 1, 0, 4);
		break ;
	case CubeFace_Top :
		normal = glm::vec3(0.f, 1.f, 0.f);
		indices = glm::ivec4(5, 4, 7, 6);
		break ;
	case CubeFace_Bottom :
		normal = glm::vec3(0.f, -1.f, 0.f);
		indices = glm::ivec4(0, 1, 2, 3);
		break ;
	default :
		return ;
	}

	addQuad(position, indices, &positions[0], normal, indexBuffer, vertexBuffer, verticesCount, indicesCount);
}

	} // namespace graffiti
} // namespace test
